package com.banshuibao.bsb_android.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.myinfterface.RecyclerItemListener;

import java.util.ArrayList;
import java.util.List;

import droidninja.filepicker.models.Document;

/**
 * Created by zyh on 2017/4/17.
 */

public class FileListAdapter extends RecyclerView.Adapter<FileListAdapter.MyViewHolder> {

    private RecyclerItemListener<Document> listener;

    private List<Document> mlist;

    private Context mContext;

    private LayoutInflater inflater;

    public FileListAdapter(Context context) {
        mContext = context;
        inflater = LayoutInflater.from(context);
        mlist = new ArrayList<>();
    }

    public void setData(List<Document> list) {
        if (mlist != null) {
            mlist.clear();
            mlist.addAll(list);
            notifyDataSetChanged();
        }
    }

    public void setListener(RecyclerItemListener<Document> listener) {
        this.listener = listener;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(inflater.inflate(R.layout.item_file, parent, false));
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        if (mlist != null && mlist.size() > 0) {
            holder.setData(mlist.get(position));
        }
    }

    @Override
    public int getItemCount() {
        return mlist != null ? mlist.size() : 0;
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView name, size;

        public MyViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.name);
            size = (TextView) itemView.findViewById(R.id.size);
        }

        public void setData(final Document data) {
            name.setText(data.getTitle());
            size.setText(Formatter.formatShortFileSize(mContext, Long.parseLong(data.getSize())));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null)
                        listener.onItemClickListener(v, data);
                }
            });
        }
    }

    public void clear() {
        if (mlist != null) {
            mlist.clear();
            mlist = null;
        }
        listener = null;
    }
}
